package com.bruan.service.impl;


import com.bruan.anno.MyLog;
import com.bruan.mapper.DeptLogMapper;
import com.bruan.mapper.DeptMapper;
import com.bruan.mapper.EmpMapper;
import com.bruan.pojo.Dept;
import com.bruan.pojo.DeptLog;
import com.bruan.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //注入mapper层接口
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogMapper deptLogMapper;

    @MyLog
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }


    /**
     * 删除部门及其员工 采用事务管理
     * @param id
     */
    @MyLog
    @Transactional(rollbackFor = Exception.class)//spring事务管理
    @Override
    public void delete(Integer id) {
        try {
            deptMapper.deleteById(id);//根据id删除部门数据
            int j = 1/0;
            empMapper.deleteByDeptId(id);//根据部门id删除部门员工
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此次解散的是"+id+"部门");
            deptLogMapper.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        //补全信息
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept search(Integer id) {
        return deptMapper.searchById(id);
    }

    @Override
    public void upadte(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
